<template>
    <div class="min-h-screen bg-gray-50 font-sans text-dark">
        <!-- 顶部导航栏 -->
        <el-header class="bg-white shadow-sm">
            <div
                class="container mx-auto h-full flex items-center justify-between"
            >
                <div class="flex items-center space-x-2">
                    <i class="fa fa-building-o text-primary text-2xl"></i>
                    <h1 class="text-xl font-semibold">智能报价解析列表</h1>
                </div>
            </div>
        </el-header>

        <!-- 主内容区 -->
        <main class="container mx-auto px-4 pt-5 pb-8">
            <!-- 批量操作按钮 -->
            <el-card class="mb-6">
                <div
                    class="flex flex-col md:flex-row md:items-center md:justify-between gap-4 mb-6"
                >
                    <div class="flex flex-wrap gap-3" style="width: 100%">
                        <el-input
                            v-model="searchInput"
                            placeholder="搜索项目编号/名称"
                            :prefix-icon="Search"
                            style="width: 300px"
                            @keyup.enter="handleSearch"
                        />
                        <el-button
                            type="default"
                            :icon="Search"
                            @click="handleSearch"
                            >筛选</el-button
                        >
                        <el-button type="default" :icon="Upload"
                            >导出</el-button
                        >
                        <el-button
                            type="primary"
                            :icon="Edit"
                            @click="openProjectModal('新增工程项目结算')"
                            >增加</el-button
                        >
                    </div>
                </div>
                <!-- 批量操作区 - 无选中时整体置灰 -->
                <div class="flex flex-wrap items-center gap-3">
                    <span class="text-sm text-gray-500"
                        >选中
                        <span class="font-medium text-primary">{{
                            selectedCount
                        }}</span>
                        项：</span
                    >
                    <el-button
                        type="danger"
                        :icon="Delete"
                        size="small"
                        :disabled="selectedCount === 0"
                        @click="handleBatchDelete"
                        >批量删除</el-button
                    >
                    <el-button
                        type="success"
                        :icon="Check"
                        size="small"
                        :disabled="selectedCount === 0"
                        @click="handleBatchSubmit"
                        >批量提交</el-button
                    >
                    <el-button
                        type="primary"
                        :icon="RefreshLeft"
                        size="small"
                        :disabled="selectedCount === 0"
                        @click="handleBatchRetrieve"
                        >批量取回</el-button
                    >
                    <el-button
                        type="info"
                        :icon="Download"
                        size="small"
                        :disabled="selectedCount === 0"
                        @click="openUploadModal"
                        >报价文件上传</el-button
                    >
                    <el-button
                        type="warning"
                        :icon="List"
                        size="small"
                        :disabled="selectedCount === 0"
                        @click="openSectionModal"
                        >分部分项查看</el-button
                    >
                </div>
            </el-card>

            <!-- 结算信息表格 -->
            <el-card>
                <div
                    class="p-4 border-b border-gray-100 flex justify-between items-center"
                >
                    <h3 class="text-lg font-semibold">结算项目列表</h3>
                    <div class="text-sm text-gray-500">
                        共
                        <span class="font-medium text-dark">{{
                            filteredProjects.length
                        }}</span>
                        条记录
                    </div>
                </div>

                <el-table
                    :data="paginatedProjects"
                    border
                    stripe
                    :header-cell-style="{ backgroundColor: '#F5F7FA' }"
                    @selection-change="handleSelectionChange"
                    row-key="id"
                    v-loading="isTableLoading"
                    loading-text="数据加载中..."
                >
                    <el-table-column
                        type="selection"
                        width="55"
                        :reserve-selection="true"
                    />
                    <el-table-column
                        prop="projectNumber"
                        label="项目编号"
                        sortable
                    />
                    <el-table-column
                        prop="projectName"
                        label="项目名称"
                        sortable
                    />
                    <el-table-column
                        prop="projectType"
                        label="项目类型"
                        sortable
                        :show-overflow-tooltip="true"
                        class="hidden md:table-cell"
                    />
                    <el-table-column
                        prop="constructionUnit"
                        label="建设单位"
                        sortable
                        :show-overflow-tooltip="true"
                        class="hidden sm:table-cell"
                    />
                    <el-table-column
                        prop="supervisionUnit"
                        label="监理单位"
                        sortable
                        :show-overflow-tooltip="true"
                        class="hidden lg:table-cell"
                    />
                    <el-table-column
                        prop="contractor"
                        label="承包商"
                        sortable
                        :show-overflow-tooltip="true"
                        class="hidden xl:table-cell"
                    />
                    <!-- 增值税结算状态 -->
                    <el-table-column prop="taxSettlement" label="增值税结算">
                        <template #default="scope">
                            <el-tag
                                :type="
                                    scope.row.taxSettlement === '是'
                                        ? 'info'
                                        : 'warning'
                                "
                                effect="light"
                            >
                                {{
                                    scope.row.taxSettlement === "是"
                                        ? "单独结算"
                                        : "合并结算"
                                }}
                            </el-tag>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 分页 - 无数据时隐藏 -->
                <div class="mt-4" v-if="filteredProjects.length > 0">
                    <el-pagination
                        @size-change="handlePageSizeChange"
                        @current-change="handleCurrentPageChange"
                        :current-page="currentPage"
                        :page-sizes="[10, 20, 50]"
                        :page-size="pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="filteredProjects.length"
                    />
                </div>
                <!-- 无数据提示 -->
                <div class="py-12 text-center" v-else>
                    <el-empty description="暂无项目数据" />
                </div>
            </el-card>
        </main>

        <!-- 页脚 -->
        <el-footer
            class="bg-white border-t border-gray-200 container mx-auto text-center text-gray-500 text-sm h-16 flex items-center justify-center"
        >
            © 2024 智能报价解析列表 版权所有
        </el-footer>

        <!-- 新增/编辑项目模态框 -->
        <el-dialog
            v-model="showProjectModal"
            :title="modalTitle"
            :width="'80%'"
            :max-width="'800px'"
            :before-close="handleCloseProjectModal"
            destroy-on-close
        >
            <el-form
                ref="projectFormRef"
                :model="formData"
                :rules="formRules"
                label-width="120px"
                class="space-y-4"
            >
                <el-row :gutter="20">
                    <!-- 必选项 -->
                    <el-col :span="12">
                        <el-form-item label="项目名称" prop="projectName">
                            <el-input
                                v-model="formData.projectName"
                                placeholder="请输入项目名称"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="项目类型" prop="projectType">
                            <el-select
                                v-model="formData.projectType"
                                placeholder="请选择项目类型"
                            >
                                <el-option
                                    label="市政基础设施"
                                    value="市政基础设施"
                                />
                                <el-option label="园林绿化" value="园林绿化" />
                                <el-option label="房建工程" value="房建工程" />
                                <el-option
                                    label="市政公用设施"
                                    value="市政公用设施"
                                />
                                <el-option label="市政管线" value="市政管线" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="建设单位" prop="constructionUnit">
                            <el-input
                                v-model="formData.constructionUnit"
                                placeholder="请输入建设单位"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item
                            label="是否单独结算增值税"
                            prop="taxSettlement"
                            label-width="200"
                        >
                            <el-radio-group v-model="formData.taxSettlement">
                                <el-radio label="是" />
                                <el-radio label="否" />
                            </el-radio-group>
                        </el-form-item>
                    </el-col>

                    <!-- 非必选项 -->
                    <el-col :span="12">
                        <el-form-item label="监理单位">
                            <el-input
                                v-model="formData.supervisionUnit"
                                placeholder="请输入监理单位"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="承包商">
                            <el-input
                                v-model="formData.contractor"
                                placeholder="请输入承包商"
                            />
                        </el-form-item>
                    </el-col>

                    <!-- 报价文件上传 -->
                    <el-col :span="24">
                        <el-form-item label="报价文件上传">
                            <el-upload
                                class="upload-demo"
                                drag
                                action="#"
                                :on-change="handleFileChange"
                                :on-remove="handleFileRemove"
                                :file-list="uploadFiles"
                                :auto-upload="false"
                                accept=".pdf,.doc,.docx,.xls,.xlsx"
                                :limit="3"
                                :on-exceed="handleFileExceed"
                            >
                                <i
                                    class="fa fa-cloud-upload text-3xl text-upload mb-2"
                                ></i>
                                <div class="el-upload__text">
                                    拖拽文件至此处或<em>点击上传</em>
                                </div>
                                <div class="el-upload__tip mt-2">
                                    支持 PDF, Excel, Word 格式，最大
                                    10MB，最多上传3个文件
                                </div>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <template #footer>
                <el-button @click="handleCloseProjectModal">取消</el-button>
                <el-button type="success" @click="saveProject">保存</el-button>
                <el-button type="primary" @click="submitProject"
                    >提交审核</el-button
                >
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import {
    ref,
    computed,
    onMounted,
    reactive,
    toRefs,
    watch,
    markRaw,
} from "vue";
import { ElMessage, ElMessageBox, ElEmpty, ElLoading } from "element-plus";
// 统一引入图标
import {
    Delete,
    Edit,
    Search,
    Upload,
    Check,
    RefreshLeft,
    Download,
    List,
    WarnTriangleFilled,
    Money,
} from "@element-plus/icons-vue";
import { useRouter } from "vue-router";

const router = useRouter();
const projectFormRef = ref(null);
const isTableLoading = ref(false); // 表格加载状态

// 状态管理 - 精简冗余字段，合并同类数据
const state = reactive({
    // 项目数据
    projects: [],
    // 搜索和分页
    searchInput: "",
    currentPage: 1,
    pageSize: 10,
    // 选中的项目ID集合
    selectedIds: new Set(),
    // 统计数据
    stats: {
        pending: 12,
        completed: 36,
        abnormal: 3,
        taxSettlement: 28,
    },
    // 模态框状态
    showProjectModal: false,
    modalTitle: "",
    currentProject: null,
    // 文件上传相关
    uploadFiles: [],
    // 表单数据（默认值优化）
    formData: {
        id: null,
        projectNumber: "",
        projectName: "",
        projectType: "",
        constructionUnit: "",
        supervisionUnit: "",
        auditor: "",
        contractor: "",
        taxSettlement: "是",
        preparedPrice: null,
        supervisionPrice: null,
        constructionPrice: null,
        costPrice: null,
        status: "待提交",
    },
    // 表单验证规则（补充必填项提示）
    formRules: {
        projectNumber: [
            { required: true, message: "请输入项目编号", trigger: "blur" },
        ],
        projectName: [
            { required: true, message: "请输入项目名称", trigger: "blur" },
        ],
        projectType: [
            { required: true, message: "请选择项目类型", trigger: "change" },
        ],
        constructionUnit: [
            { required: true, message: "请输入建设单位", trigger: "blur" },
        ],
        taxSettlement: [
            {
                required: true,
                message: "请选择是否单独结算增值税",
                trigger: "change",
            },
        ],
        preparedPrice: [
            { required: true, message: "请输入结算编制价", trigger: "blur" },
            {
                type: "number",
                message: "请输入有效的非负数字",
                trigger: "blur",
                min: 0,
            },
        ],
    },
    // 导航状态
    activeMenu: "settlement",
});

// 解构响应式状态
const {
    projects,
    searchInput,
    currentPage,
    pageSize,
    selectedIds,
    stats,
    showProjectModal,
    modalTitle,
    currentProject,
    uploadFiles,
    formData,
    formRules,
    activeMenu,
} = toRefs(state);

// 统计卡片配置（减少模板重复代码）
const statCards = [
    {
        label: "待审核项目",
        key: "pending",
        icon: markRaw(List), // 标记为非响应式
        bgClass: "bg-primary/10",
        textClass: "text-primary",
        iconColor: "#165DFF",
    },
    {
        label: "已完成项目",
        key: "completed",
        icon: markRaw(Check), // 标记为非响应式
        bgClass: "bg-success/10",
        textClass: "text-success",
        iconColor: "#52C41A",
    },
    {
        label: "异常项目",
        key: "abnormal",
        icon: markRaw(WarnTriangleFilled), // 标记为非响应式（修复警告核心）
        bgClass: "bg-warning/10",
        textClass: "text-warning",
        iconColor: "#FAAD14",
    },
    {
        label: "增值税结算",
        key: "taxSettlement",
        icon: markRaw(Money), // 标记为非响应式（修复警告核心）
        bgClass: "bg-[#F1EAFA]",
        textClass: "text-[#7E46D2]",
        iconColor: "#7E46D2",
    },
];

// 初始化项目数据（添加加载状态）
onMounted(async () => {
    isTableLoading.value = true;
    try {
        // 模拟API请求延迟
        await new Promise((resolve) => setTimeout(resolve, 500));
        projects.value = [
            {
                id: 1,
                projectNumber: "XM-2023-0568",
                projectName: "城南新区道路拓宽改造工程",
                projectType: "市政基础设施",
                constructionUnit: "市城市建设投资集团",
                supervisionUnit: "恒信工程监理",
                contractor: "宏业建筑工程",
                preparedPrice: 12568900,
                costPrice: 12320000,
                taxSettlement: "是",
                status: "已完成",
            },
            {
                id: 2,
                projectNumber: "XM-2023-0572",
                projectName: "滨江公园景观提升工程",
                projectType: "园林绿化",
                constructionUnit: "市园林绿化管理处",
                supervisionUnit: "景程监理公司",
                contractor: "绿源景观工程",
                preparedPrice: 8750000,
                costPrice: 8620500,
                taxSettlement: "否",
                status: "审核中",
            },
            {
                id: 3,
                projectNumber: "XM-2023-0589",
                projectName: "城东污水处理厂扩建工程",
                projectType: "市政公用设施",
                constructionUnit: "市水务集团",
                supervisionUnit: "华信工程监理",
                contractor: "东方建设工程",
                preparedPrice: 25680000,
                costPrice: null,
                taxSettlement: "是",
                status: "待提交",
            },
            {
                id: 4,
                projectNumber: "XM-2023-0601",
                projectName: "老旧小区改造工程（一期）",
                projectType: "房建工程",
                constructionUnit: "市住房保障中心",
                supervisionUnit: "诚信监理公司",
                contractor: "惠民建筑工程",
                preparedPrice: 18950000,
                costPrice: 18560300,
                taxSettlement: "否",
                status: "待提交",
            },
            {
                id: 5,
                projectNumber: "XM-2023-0615",
                projectName: "城市供水管道改造工程",
                projectType: "市政管线",
                constructionUnit: "市自来水公司",
                supervisionUnit: "永安工程监理",
                contractor: "管道工程公司",
                preparedPrice: 9870000,
                costPrice: 9650000,
                taxSettlement: "是",
                status: "审核中",
            },
        ];
    } catch (error) {
        ElMessage.error("数据加载失败，请刷新重试");
        console.error("初始化失败:", error);
    } finally {
        isTableLoading.value = false;
    }
});

// 过滤项目数据（优化搜索逻辑）
const filteredProjects = computed(() => {
    if (!searchInput.value.trim()) return projects.value;
    const searchStr = searchInput.value.toLowerCase().trim();
    return projects.value.filter(
        (project) =>
            project.projectNumber.toLowerCase().includes(searchStr) ||
            project.projectName.toLowerCase().includes(searchStr)
    );
});

// 分页处理（简化计算逻辑）
const paginatedProjects = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    return filteredProjects.value.slice(start, end);
});

// 选中数量计算（优化性能）
const selectedCount = computed(() => {
    return Array.from(selectedIds.value).length;
});

// 根据状态获取标签类型（简化判断逻辑）
const getStatusType = (status) => {
    const statusMap = {
        已完成: "success",
        审核中: "warning",
        待提交: "info",
    };
    return statusMap[status] || "danger";
};

// 处理选择变化（简化逻辑）
const handleSelectionChange = (selection) => {
    selectedIds.value.clear();
    selection.forEach((item) => selectedIds.value.add(item.id));
};

// 分页事件（保持简洁）
const handlePageSizeChange = (size) => {
    pageSize.value = size;
    currentPage.value = 1;
};
const handleCurrentPageChange = (page) => {
    currentPage.value = page;
};

// 处理搜索（增加防抖逻辑）
let searchTimer = null;
const handleSearch = () => {
    clearTimeout(searchTimer);
    searchTimer = setTimeout(() => {
        currentPage.value = 1;
        selectedIds.value.clear();
    }, 300);
};

// 监听搜索输入变化（移除冗余判断）
watch(searchInput, () => {
    selectedIds.value.clear();
});

// 打开项目模态框（优化表单重置逻辑）
const openProjectModal = (title, project = null) => {
    modalTitle.value = title;
    currentProject.value = project;
    uploadFiles.value = [];

    if (project) {
        // 编辑模式 - 深拷贝避免原数据污染
        formData.value = JSON.parse(JSON.stringify(project));
    } else {
        // 新增模式 - 重置表单
        projectFormRef.value?.resetFields();
        formData.value = {
            id: null,
            projectNumber: "",
            projectName: "",
            projectType: "",
            constructionUnit: "",
            supervisionUnit: "",
            auditor: "",
            contractor: "",
            taxSettlement: "是",
            preparedPrice: null,
            supervisionPrice: null,
            constructionPrice: null,
            costPrice: null,
            status: "待提交",
        };
    }

    showProjectModal.value = true;
};

// 关闭项目模态框（简化逻辑）
const handleCloseProjectModal = () => {
    showProjectModal.value = false;
    uploadFiles.value = [];
};

// 保存项目（优化提示逻辑）
const saveProject = async () => {
    try {
        await projectFormRef.value.validate();
        const isEdit = !!currentProject.value;

        if (isEdit) {
            // 编辑模式
            const index = projects.value.findIndex(
                (p) => p.id === currentProject.value.id
            );
            if (index !== -1) projects.value[index] = { ...formData.value };
        } else {
            // 新增模式
            const newId = Math.max(...projects.value.map((p) => p.id), 0) + 1;
            projects.value.unshift({ ...formData.value, id: newId });
        }

        ElMessage.success(isEdit ? "项目信息已保存" : "新项目已创建");
        showProjectModal.value = false;
    } catch (error) {
        console.error("表单验证失败:", error);
    }
};

// 提交项目审核（合并重复逻辑）
const submitProject = async () => {
    try {
        await projectFormRef.value.validate();
        const isEdit = !!currentProject.value;
        const submitData = { ...formData.value, status: "审核中" };

        if (isEdit) {
            const index = projects.value.findIndex(
                (p) => p.id === currentProject.value.id
            );
            if (index !== -1) projects.value[index] = submitData;
        } else {
            const newId = Math.max(...projects.value.map((p) => p.id), 0) + 1;
            projects.value.unshift({ ...submitData, id: newId });
        }

        ElMessage.success("项目已提交审核");
        showProjectModal.value = false;
    } catch (error) {
        console.error("表单验证失败:", error);
    }
};

// 打开分部分项模态框（简化跳转逻辑）
const openSectionModal = () => {
    router.push("/settMgmt/breakdownQuotes");
};

// 打开上传模态框（优化日志输出）
const openUploadModal = () => {
    router.push("/settMgmt/bidDocsUpload");
};

// 文件上传相关方法（增加文件限制处理）
const handleFileChange = (file, fileList) => {
    uploadFiles.value = fileList;
};
const handleFileRemove = (file, fileList) => {
    uploadFiles.value = fileList;
};
const handleFileExceed = (files) => {
    ElMessage.warning(`最多只能上传3个文件，本次选择了${files.length}个文件`);
};

// 批量操作方法（统一提示逻辑）
const handleBatchDelete = () => {
    ElMessageBox.confirm(
        `确定要删除选中的${selectedCount.value}个项目吗？此操作不可撤销。`,
        "确认批量删除",
        { type: "warning" }
    ).then(() => {
        const idsToDelete = new Set(selectedIds.value);
        projects.value = projects.value.filter((p) => !idsToDelete.has(p.id));
        selectedIds.value.clear();
        ElMessage.success("选中项目已删除");
    });
};

const handleBatchSubmit = () => {
    ElMessageBox.confirm(
        `确定要提交选中的${selectedCount.value}个项目进行审核吗？`,
        "确认批量提交",
        { type: "info" }
    ).then(() => {
        projects.value.forEach((p) => {
            if (selectedIds.value.has(p.id)) p.status = "审核中";
        });
        selectedIds.value.clear();
        ElMessage.success("选中项目已提交审核");
    });
};

const handleBatchRetrieve = () => {
    ElMessageBox.confirm(
        `确定要取回选中的${selectedCount.value}个项目吗？`,
        "确认批量取回",
        { type: "info" }
    ).then(() => {
        projects.value.forEach((p) => {
            if (selectedIds.value.has(p.id)) p.status = "待提交";
        });
        selectedIds.value.clear();
        ElMessage.success("选中项目已取回");
    });
};
</script>

<style scoped>
/* 统一颜色变量 */
:deep(.text-primary) {
    color: #165dff !important;
}
:deep(.text-upload) {
    color: #409eff !important;
}
:deep(.text-tax) {
    color: #7e46d2 !important;
}

/* 优化卡片 hover 效果 */
:deep(.el-card) {
    border: none !important;
    border-radius: 8px !important;
}

/* 优化分页样式 */
:deep(.el-pagination) {
    display: flex;
    justify-content: center;
}

/* 优化上传组件样式 */
:deep(.el-upload--drag) {
    border: 2px dashed #dcdfe6 !important;
    border-radius: 6px !important;
}
:deep(.el-upload--drag:hover) {
    border-color: #409eff !important;
}

/* 优化表格样式 */
:deep(.el-table__header th) {
    font-weight: 500 !important;
}
:deep(.el-table__body tr:hover > td) {
    background-color: #f9fafb !important;
}

/* 优化按钮样式 */
:deep(.el-button) {
    border-radius: 4px !important;
}
</style>
